package k8s

import (
	istioclient "istio.io/client-go/pkg/clientset/versioned"
	istioinformers "istio.io/client-go/pkg/informers/externalversions"
	"k8s.io/client-go/informers"
	kube "k8s.io/client-go/kubernetes"
	"time"
)

// default re-sync period for all informer factories
const defaultResync = 600 * time.Second

// 可以扩展为支持自定义资源的informers
type K8sInformerInterface interface {
	KubernetesSharedInformerFactory() informers.SharedInformerFactory
	IstioSharedInformerFactory() istioinformers.SharedInformerFactory
	Start(stopCh <-chan struct{})
}

type InformerClient struct {
	informerFactory      informers.SharedInformerFactory
	istioInformerFactory istioinformers.SharedInformerFactory
}

func (f *InformerClient) KubernetesSharedInformerFactory() informers.SharedInformerFactory {
	return f.informerFactory
}

func (f *InformerClient) IstioSharedInformerFactory() istioinformers.SharedInformerFactory {
	return f.istioInformerFactory
}

func (f *InformerClient) Start(stopCh <-chan struct{}) {
	if f.informerFactory != nil {
		f.informerFactory.Start(stopCh)
	}

}

func NewInformerFactory(client kube.Interface, istioClient istioclient.Interface) (K8sInformerInterface, error) {

	// 初始化缓存client
	factory := &InformerClient{}

	if client != nil {
		factory.informerFactory = informers.NewSharedInformerFactory(client, defaultResync)
	}

	//初始化istio client
	if istioClient != nil {
		factory.istioInformerFactory = istioinformers.NewSharedInformerFactory(istioClient, defaultResync)
	}
	return factory, nil

}
